<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="用户列表"></n-card>
    </div>
    <n-grid x-gap="12" :cols="4">
      <n-gi span="1">
        <n-card :bordered="false" class="mt-4 proCard">
          <n-tree block-line cascade :virtual-scroll="true" :data="deptTrees" style="max-height: 650px; overflow: hidden"
            @update:selected-keys="selectedTree" @update:expanded-keys="onExpandedKeys" />
        </n-card>
      </n-gi>
      <n-gi span="3">
        <n-card :bordered="false" class="mt-4 proCard">
          <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
            <template #statusSlot="{ model, field }">
              <n-input v-model:value="model[field]" />
            </template>
          </BasicForm>
          <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
            :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :bordered="false">
            <template #tableTitle>
              <n-button type="primary" :on-click="handleEdit.bind(null, {}, true)">
                <template #icon>
                  <n-icon>
                    <PlusOutlined />
                  </n-icon>
                </template>
                添加用户
              </n-button>
            </template>
            <template #action>
              <TableAction />
            </template>
          </BasicTable>
        </n-card>
      </n-gi>
    </n-grid>



    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle"
      style="width: 720px;border-radius: 8px;">
      <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="用户姓名" path="name">
            <n-input maxlength="100" show-count placeholder="请输入用户姓名" v-model:value="fromValues.name" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="账号" path="username">
            <n-input maxlength="100" show-count placeholder="请输入账号" v-model:value="fromValues.username" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="手机号" path="mobile">
            <n-input maxlength="11" show-count style="width: 100%;" placeholder="请输入手机号"
              v-model:value="fromValues.mobile" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="邮箱" path="email">
            <n-input maxlength="100" show-count style="width: 100%;" placeholder="请输入邮箱"
              v-model:value="fromValues.email" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="状态" path="accountNonLocked">
            <n-select v-model:value="fromValues.accountNonLocked" filterable placeholder="请选择状态" :options="lockStatus" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="性别" path="sex">
            <n-select v-model:value="fromValues.sex" filterable placeholder="请选择性别" :options="sexOptions" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="部门" path="deptId">
            <n-tree-select :options="deptTrees" v-model:value="fromValues.deptId" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="生日" path="pickerDate">
            <n-date-picker style="width: 100%;" v-model:value="fromValues.pickerDate" type="date" />
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="描述" path="description">
            <n-input maxlength="300" show-count type="textarea" :autosize="{
              minRows: 3,
              maxRows: 5
            }" v-model:value="fromValues.description" filterable placeholder="请输入描述" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
      <div style="justify-content: end;display: flex;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleCloseModel">
            取消
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </div>
    </n-modal>


    <n-drawer v-model:show="showDrawer" :width="720">
      <n-drawer-content :title="drawerTitle" :native-scrollbar="false">
        <n-descriptions label-placement="left" bordered>
          <n-descriptions-item label="账号" :span="2">
            {{ userEntity.username }}
          </n-descriptions-item>
          <n-descriptions-item label="姓名" :span="2">
            {{ userEntity.name }}
          </n-descriptions-item>
          <n-descriptions-item label="手机" :span="2">
            {{ userEntity.mobile }}
          </n-descriptions-item>
          <n-descriptions-item label="邮箱" :span="2">
            {{ userEntity.email }}
          </n-descriptions-item>
          <n-descriptions-item label="性别" :span="2">
            <n-tag v-if="userEntity.sex === 0" type="success">男</n-tag>
            <n-tag v-if="userEntity.sex === 1" type="error">女</n-tag>
          </n-descriptions-item>
          <n-descriptions-item label="状态" :span="2">
            <n-tag v-if="userEntity.accountNonLocked" type="success">正常</n-tag>
            <n-tag v-if="!userEntity.accountNonLocked" type="error">锁定</n-tag>
          </n-descriptions-item>
          <n-descriptions-item label="生日" :span="2">
            {{ userEntity.birthday }}
          </n-descriptions-item>
          <n-descriptions-item label="创建人" :span="2">
            {{ userEntity.createdBy }}
          </n-descriptions-item>
          <n-descriptions-item label="更新人" :span="2">
            {{ userEntity.updatedBy }}
          </n-descriptions-item>
          <n-descriptions-item label="创建时间" :span="2">
            {{ userEntity.createdTime }}
          </n-descriptions-item>
          <n-descriptions-item label="更新时间" :span="2">
            {{ userEntity.updatedTime }}
          </n-descriptions-item>
          <n-descriptions-item label="头像" :span="2">
            <n-image :show-toolbar="false" width="60" height="60" object-fit="cover" :src="userEntity.avatar" />
          </n-descriptions-item>
        </n-descriptions>
        <div class="moss-segment">
          <n-tabs type="segment" @update:value="handleUpdateValue" default-value="tenant">
            <n-tab name="tenant">租户信息</n-tab>
            <n-tab name="dept">部门信息</n-tab>
            <n-tab name="role">角色信息</n-tab>
            <n-tab name="postion">职位信息</n-tab>
          </n-tabs>
          <n-card style="margin-top: 10px;">
            <n-spin :show="spinShow">
              <div v-if="tabKey === 'tenant'">
                <MossEmpty v-if="tenantEntity.id === null" />
                <n-grid :y-gap="8" x-gap="12" :cols="2" v-if="tenantEntity.id !== null">
                  <n-gi>
                    租户名称：{{ tenantEntity.tenantName }}
                  </n-gi>
                  <n-gi>
                    租户地址：{{ tenantEntity.tenantAddress }}
                  </n-gi>
                  <n-gi>
                    租户电话：{{ tenantEntity.tenantPhone }}
                  </n-gi>
                  <n-gi>
                    <span>门头照片：</span>
                    <n-image v-if="tenantEntity.tenantDoorPhoto !== null" :show-toolbar="false" width="60" height="60"
                      object-fit="cover" :src="tenantEntity.tenantDoorPhoto" />
                  </n-gi>
                </n-grid>
              </div>
              <div v-if="tabKey === 'dept'">
                <MossEmpty v-if="deptEntity.id === null" />
                <n-grid :y-gap="8" x-gap="12" :cols="2" v-if="deptEntity.id !== null">
                  <n-gi>
                    部门名称：{{ deptEntity.name }}
                  </n-gi>
                  <n-gi>
                    备注：{{ deptEntity.description }}
                  </n-gi>
                </n-grid>
              </div>
              <div v-if="tabKey === 'role'">
                <n-grid :y-gap="8" x-gap="12" :cols="3" v-for="item in roleList">
                  <n-gi>
                    角色名称：{{ item.name }}
                  </n-gi>
                  <n-gi>
                    角色CODE：{{ item.code }}
                  </n-gi>
                  <n-gi>
                    角色说明：{{ item.description }}
                  </n-gi>
                </n-grid>
              </div>
              <div v-if="tabKey === 'postion'">
                <BasicTable :columns="positionColumns" :request="loadUserPosition" :row-key="(row) => row.id"
                  ref="actionPositionRef" id="moss-basicTable" :bordered="false" :pagination="false">
                  <template #action>
                    <TableAction />
                  </template>
                </BasicTable>
              </div>
            </n-spin>
          </n-card>
        </div>
      </n-drawer-content>
    </n-drawer>


    <n-modal v-model:show="showRoleModal" :show-icon="false" preset="dialog" :title="editRoleTitle"
      style="width: 480px;border-radius: 8px;">
      <n-select placeholder="选择角色" multiple :options="rolesOptions" v-model:value="roleFromValues.roleIds"
        @update:value="handleUpdateRole" />
      <div style="justify-content: end;display: flex; margin-top: 15px;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleColseRole">
            取消
          </n-button>
          <n-popconfirm placement="top-end" @positive-click="confirmRoleForm">
            <template #trigger>
              <n-button type="primary" :loading="formBtnLoading">提交</n-button>
            </template>
            重新授权后该用户所有权限将会发生变化，您确定要这样操作吗？
          </n-popconfirm>
        </n-space>
      </div>
    </n-modal>

    <!-- 锁定 -->
    <n-modal v-model:show="showLockModal" :show-icon="false" preset="dialog" :title="editLockTitle">
      <n-form :model="userLockFrom" :rules="lockRules" ref="formLockRef" label-placement="top" :label-width="120"
        class="py-4">
        <n-form-item v-if="showLockDate" label="解锁时间" path="pickerUnlockDate">
          <n-date-picker style="width: 100%;" v-model:value="userLockFrom.pickerUnlockDate" type="datetime" />
        </n-form-item>
        <n-form-item v-if="showLockDate" label="锁定原因" path="lockReason">
          <n-input maxlength="300" show-count type="textarea" :autosize="{
            minRows: 3,
            maxRows: 5
          }" v-model:value="userLockFrom.lockReason" filterable placeholder="请输入锁定原因" />
        </n-form-item>
        <n-form-item v-if="!showLockDate" label="解锁原因" path="unlockReason">
          <n-input maxlength="300" show-count type="textarea" :autosize="{
            minRows: 3,
            maxRows: 5
          }" v-model:value="userLockFrom.unlockReason" filterable placeholder="请输入解锁原因" />
        </n-form-item>
      </n-form>
      <div style="justify-content: end;display: flex;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleCloseLockModal">
            取消
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmLockForm">提交</n-button>
        </n-space>
      </div>
    </n-modal>

    <!-- 转岗 -->
    <n-modal v-model:show="showPostionModal" :show-icon="false" preset="dialog" title="用户转岗">
      <n-tree block-line checkable expand-on-click :virtual-scroll="true" :data="treeData"
        :expandedKeys="expandedPostionKeys" style="max-height: 650px; overflow: hidden"
        @update:expanded-keys="onExpandedPostionKeys" :default-checked-keys="positionIds"
        @update:checked-keys="updateCheckedKeys" />
      <div style="justify-content: end;display: flex; margin-top: 10px;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleClosePosition">
            取消
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmPosition">提交</n-button>
        </n-space>
      </div>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, h, onMounted, unref } from 'vue';
import { useMessage, useDialog, type FormRules } from 'naive-ui';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { BasicTable, TableAction } from '@/components/Table';
import {
  usersPages, deptTree, removeUser, adminAddUser, adminUpdUser,
  tenantInfoByUserId, deptInfo, roleInfoByUserId, saveBatchUserRole, roleList as roleListApi, resetPassword,
  lockAccount, unlockAccount, userDepart
} from '@/api/system/user';
import { userPositionPage, transfer, userPositions, positionTree } from '@/api/system/position';
import { dictGroup } from '@/api/system/dict';
import { columns, positionColumns } from './columns';
import { EditOutlined, PlusOutlined, SnippetsOutlined, SecurityScanOutlined } from '@vicons/antd';
import { ResultEnum } from '@/enums/httpEnum';
import { formatToDate, formatToDateTime } from '@/utils/dateUtil';
import { lockStatus } from '@/utils/convert';
import MossEmpty from '@/components/Custom/MossEmpty.vue';
const message = useMessage();
const actionRef = ref();
const actionPositionRef = ref();
const showModal = ref(false);
const showDrawer = ref(false);
const drawerTitle = ref('');
const formBtnLoading = ref(false);
const editTitle = ref('');
const isAdd = ref(true);
const formRef: any = ref(null);
const dialog = useDialog();
const tabKey = ref('tenant');
const spinShow = ref(false);
const showRoleModal = ref(false);
const editRoleTitle = ref('');
const roleList: any = ref(null);
const sexOptions = ref([]);
let expandedKeys = ref([]);
let deptTrees = ref([]);
let fromValues = reactive({
  id: null,
  name: '',
  username: '',
  mobile: '',
  email: '',
  accountNonLocked: null,
  sex: null,
  roleIds: null,
  deptId: null,
  birthday: '',
  description: '',
  pickerDate: null
});

let userEntity = reactive({
  id: null,
  /** 用户名 */
  username: '',
  /** 用户姓名 */
  name: '',
  /** 用户手机 */
  mobile: '',
  /** 简介 */
  description: '',
  /** 是否未锁定 */
  accountNonLocked: null,
  /** 用户邮箱 */
  email: '',
  /** 租户ID */
  tenantId: null,
  /** 用户头像 */
  avatar: '',
  /** 用户性别（0男，1女） */
  sex: null,
  /** 生日*/
  birthday: null,
  /** 用户部门ID */
  deptId: null,
  createdBy: '',
  updatedBy: '',
  createdTime: null,
  updatedTime: null
});
const defaultTenant = () => ({
  id: null,
  /*** 租户名称*/
  tenantName: '',
  /*** 租户地址*/
  tenantAddress: '',
  /*** 租户电话*/
  tenantPhone: '',
  /*** 租户邮箱*/
  tenantEmail: '',
  /*** 门头照*/
  tenantDoorPhoto: '',
})
let tenantEntity = reactive(defaultTenant());
const defaultDept = () => ({
  id: null,
  /** 部门名称 */
  name: '',
  /** 部门级别*/
  level: null,
  /** 部门排序*/
  orderNum: null,
  /** 描述 */
  description: '',
})
let deptEntity = reactive(defaultDept());
let roleFromValues = reactive({
  userId: null,
  roleIds: null
});

const showPostionModal = ref<boolean>(false);
const treeData = ref([]);
let expandedPostionKeys = ref([]);
const selectPostionKeys: any = ref(null);
let positionIds = ref([]);
const currentUser = ref(0)
function onExpandedPostionKeys(keys) {
  expandedPostionKeys.value = keys;
}
/**
 * 选择职位
 * @param keys 
 */
function updateCheckedKeys(keys: Array<string | number>) {
  selectPostionKeys.value = keys;
}

const handleClosePosition = () => {
  showPostionModal.value = false;
  selectPostionKeys.value = [];
}

/**
 * 角色授权菜单信息
 * @param record 
 */
const handlePostionEdit = (record: Recordable) => {
  message.loading('用户岗位信息加载中...', {
    duration: 500,
    onAfterLeave: async () => {
      currentUser.value = record.id;
      const ids = await userPositions({ id: record.id });
      positionIds.value = ids;
      showPostionModal.value = true;
    }
  })
}

/**
 * 角色授权菜单
 */
const confirmPosition = () => {
  formBtnLoading.value = true;
  setTimeout(async () => {
    formBtnLoading.value = true;
    const fromValues = { userId: currentUser.value, positionIds: selectPostionKeys.value ? selectPostionKeys.value : positionIds.value };
    const data = await transfer(fromValues);
    if (data.code !== ResultEnum.SUCCESS) {
      const resultMsg = data.data ? data.data : '';
      message.error(data.mesg + '-' + resultMsg);
    }
    if (data.code === ResultEnum.SUCCESS) {
      message.success(data.mesg);
      showPostionModal.value = false;
    }
    formBtnLoading.value = false;
  }, 200);
}


let rolesOptions: any = []
const formLockRef: any = ref(null);
const showLockModal = ref<boolean>(false);
const editLockTitle = ref<string>('');
const showLockDate = ref<boolean>(false);
const lockStatusRef = ref<boolean>(false);
const defaultLock = () => ({
  /** 用户id*/
  userId: null,
  /**锁定原因*/
  lockReason: '',
  /**解锁时间*/
  unlockTime: '',
  /**解锁原因*/
  unlockReason: '',
  pickerUnlockDate: null,
})
let userLockFrom = reactive(defaultLock());
/**
 * 锁定解锁
 * @param record 
 * @param isLock 
 */
const lockUser = (record, isLock: boolean) => {
  userLockFrom.userId = record.id;
  editLockTitle.value = isLock ? `锁定用户${record.name}` : `解锁用户${record.name}`;
  showLockDate.value = isLock;
  lockStatusRef.value = isLock;
  showLockModal.value = true;
}
/**
 * 关闭锁定解锁弹框
 */
const handleCloseLockModal = () => {
  showLockModal.value = false;
  userLockFrom = Object.assign(unref(userLockFrom), defaultTenant());
}
const lockRules: FormRules = {
  lockReason: {
    required: true,
    message: '请输入锁定原因',
    trigger: 'blur',
  },
  pickerUnlockDate: {
    type: 'date',
    required: true,
    message: '请选择解锁时间',
    trigger: 'blur',
  },
  unlockReason: {
    required: true,
    message: '请输入解锁原因',
    trigger: 'blur',
  },
}
const resetLockFrom = () => {
  userLockFrom = Object.assign(unref(userLockFrom), defaultLock());
}
/**
 * 新增编辑提交数据
 * @param e 
 */
const confirmLockForm = (e: any) => {
  e.preventDefault();
  formLockRef.value.validate(async (errors) => {
    if (!errors) {
      formBtnLoading.value = true;
      if (userLockFrom.pickerUnlockDate) {
        userLockFrom.unlockTime = formatToDateTime(new Date(userLockFrom.pickerUnlockDate));
      }
      const data = lockStatusRef.value ? await lockAccount(userLockFrom) : await unlockAccount(userLockFrom);
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        showLockModal.value = false;
        resetLockFrom();
        reloadTable();
      }
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

/**
 * 表格查询参数定义
 */
const schemas: FormSchema[] = [
  {
    field: 'name',
    component: 'NInput',
    label: '用户姓名',
    componentProps: {
      placeholder: '请输入用户姓名',
    },
  },
  {
    field: 'username',
    component: 'NInput',
    label: '账号',
    componentProps: {
      placeholder: '请输入账号',
    },
  },
  {
    field: 'mobile',
    component: 'NInput',
    label: '手机号',
    componentProps: {
      placeholder: '请输入手机号',
    },
  },
  {
    field: 'email',
    component: 'NInput',
    label: '邮箱',
    componentProps: {
      placeholder: '请输入邮箱',
    },
  },
  {
    field: 'accountNonLocked',
    component: 'NSelect',
    label: '状态',
    componentProps: {
      placeholder: '请选择状态',
      options: lockStatus,
    },
  },
];
/**
 * 表格查询注册
 */
const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});
const actionColumn = reactive({
  width: 290,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'text',
      actions: createActions(record),
      dropDownActions: [
        {
          label: '重置密码',
          key: 'RESET_PASSWORD',
          ifShow: () => {
            return true;
          },
          auth: ['base_sys_user_reset_pwd'],
        },
        {
          label: '锁定账号',
          key: 'LOCK_ACCOUNT',
          ifShow: () => {
            return record.accountNonLocked ? true : false;
          },
          auth: ['base_sys_user_lock_account'],
        },
        {
          label: '解锁账号',
          key: 'UNLOCK_ACCOUNT',
          ifShow: () => {
            return record.accountNonLocked ? false : true;
          },
          auth: ['base_sys_user_unlock_account'],
        },
        {
          label: '员工转岗',
          key: 'USER_TRANSFER',
          ifShow: () => {
            return true;
          },
          auth: ['base_sys_user_position_transfer'],
        }, {
          label: '员工离职',
          key: 'USER_DEPART',
          ifShow: () => {
            return record.tenantId ? true : false;
          },
          auth: ['base_sys_user_userDepart'],
        },
        {
          label: '删除',
          key: 'DEL_USER',
          ifShow: () => {
            return true;
          },
          auth: ['base_sys_user_del'],
        },
      ],
      select: (key) => {
        if (key === 'RESET_PASSWORD') {
          resetUserPassword(record);
        }
        if (key === 'DEL_USER') {
          handleDelete(record);
        }
        if (key === 'LOCK_ACCOUNT') {
          lockUser(record, true);
        }
        if (key === 'UNLOCK_ACCOUNT') {
          lockUser(record, false);
        }
        if (key === 'USER_TRANSFER') {
          handlePostionEdit(record);
        }
        if (key === 'USER_DEPART') {
          handleUserDepart(record);
        }
      },
    });
  },
});

/**
 * 删除确认
 * @param record 
 */
const handleUserDepart = (record: Recordable) => {
  dialog.warning({
    title: '警告',
    content: `确定${record.name}离职吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const data = await userDepart({ id: record.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        reloadTable();
      }
    },
  })
}

async function resetUserPassword(record) {
  const data = await resetPassword({ id: record.id });
  if (data.code !== ResultEnum.SUCCESS) {
    const resultMsg = data.data ? data.data : '';
    message.error(data.mesg + '-' + resultMsg);
  }
  if (data.code === ResultEnum.SUCCESS) {
    message.success(data.mesg);
  }
}

function createActions(record) {
  return [
    {
      label: '编辑',
      type: 'primary',
      icon: EditOutlined,
      onClick: handleEdit.bind(null, record, false),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
    {
      label: '详情',
      type: 'success',
      icon: SnippetsOutlined,
      onClick: handleShowDrawer.bind(null, record),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
    {
      label: '授权',
      type: 'warning',
      icon: SecurityScanOutlined,
      onClick: handleAuthRole.bind(null, record),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
  ];
}
const rules: FormRules = {
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入用户姓名',
  },
  username: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入账号',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  mobile: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入手机号',
    },
    { pattern: /^1[3456789]\d{9}$/, trigger: ['blur', 'input'], message: '请输入正确的手机号' },
  ],
  deptId: {
    required: true,
    //trigger: 'change',
    message: '请选择部门',
  },
  email: {
    pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, trigger: ['blur', 'input'], message: '请输入正确的邮箱'
  }
};
const loadDataTable = async (res: any) => {
  return await usersPages({ ...getFieldsValue(), ...res });
};
/**
 * 加载部门数据
 */
const getDeptTree = async () => {
  const data = await deptTree({});
  deptTrees.value = data;
}
/**
 * 点击树节点重新加载表格数据
 * @param keys 
 */
function selectedTree(keys) {
  console.log(keys);
  actionRef.value.reload({ deptId: keys[0] });
}
/**
 * 加载角色数据
 */
const getRoleList = async () => {
  const data = await roleListApi({});
  if (data !== null) {
    data.forEach(item => {
      rolesOptions.push({ label: item.name, value: item.id });
    });
  }
}

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}
/**
 * 查询
 */
function handleSubmit() {
  reloadTable();
}
/**
 * 重置查询
 */
function handleReset() {
  reloadTable();
}
function resetFrom() {
  fromValues = Object.assign(fromValues, {
    id: null,
    name: '',
    username: '',
    mobile: '',
    email: '',
    accountNonLocked: null,
    sex: null,
    roleIds: null,
    deptId: null,
    birthday: '',
    description: '',
    pickerDate: null
  });
}
/**
 * 新增编辑提交数据
 * @param e 
 */
function confirmForm(e: any) {
  e.preventDefault();
  formBtnLoading.value = true;
  formRef.value.validate((errors) => {
    if (!errors) {
      setTimeout(async () => {
        showModal.value = false;
        if (isAdd.value === true) {
          if (fromValues.pickerDate !== null) {
            fromValues.birthday = formatToDate(new Date(fromValues.pickerDate));
          }
          const data = await adminAddUser(fromValues);
          if (data.code !== ResultEnum.SUCCESS) {
            const resultMsg = data.data ? data.data : '';
            message.error(data.mesg + '-' + resultMsg);
          }
          if (data.code === ResultEnum.SUCCESS) {
            message.success(data.mesg);
            showModal.value = false;
            resetFrom();
            reloadTable();
          }
        } else {
          if (fromValues.pickerDate !== null) {
            fromValues.birthday = formatToDate(new Date(fromValues.pickerDate));
          }
          const data = await adminUpdUser(fromValues);
          if (data.code !== ResultEnum.SUCCESS) {
            const resultMsg = data.data ? data.data : '';
            message.error(data.mesg + '-' + resultMsg);
          }
          if (data.code === ResultEnum.SUCCESS) {
            message.success(data.mesg);
            showModal.value = false;
            resetFrom();
            reloadTable();
          }
        }
        formBtnLoading.value = false;
      }, 200);
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

function handleEdit(record: Recordable, addStatus: boolean) {
  showModal.value = true;
  isAdd.value = addStatus;
  if (addStatus) {
    editTitle.value = `新增用户`;
  } else {
    editTitle.value = `编辑 ${record.name}`;
    if (record.birthday !== null) {
      record.pickerDate = Date.parse(record.birthday);
    }
    fromValues = Object.assign(fromValues, record);
  }
}
/**
 * 新增编辑关闭model
 */
function handleCloseModel() {
  resetFrom();
  showModal.value = false;
}
/**
 * 删除确认
 * @param record 
 */
function handleDelete(record: Recordable) {
  dialog.warning({
    title: '警告',
    content: `确定删除${record.name}吗？`,
    positiveText: '确定',
    negativeText: '取消',
    style: "border-radius: 8px;",
    onPositiveClick: async () => {
      const data = await removeUser({ userId: record.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        showModal.value = false;
        reloadTable();
      }
    },
  })
}
/**
 * 详情
 * @param record 
 */
function handleShowDrawer(record: Recordable) {
  drawerTitle.value = record.name;
  spinShow.value = true;
  userEntity = Object.assign(userEntity, record);
  setTimeout(async () => {
    tenantInfo();
    spinShow.value = false;
  }, 300);
  showDrawer.value = true;
}
/**
 * 用户的租户信息
 */
async function tenantInfo() {
  if (userEntity.id) {
    const data = await tenantInfoByUserId({ id: userEntity.id });
    tenantEntity = data ? Object.assign(tenantEntity, data) : Object.assign(unref(tenantEntity), defaultTenant());
  } else {
    tenantEntity = Object.assign(unref(tenantEntity), defaultTenant());
  }
}
/**
 * 用户的部门信息
 */
async function userDeptInfo() {
  if (userEntity.deptId) {
    const data = await deptInfo({ id: userEntity.deptId });
    deptEntity = data ? Object.assign(deptEntity, data) : Object.assign(unref(deptEntity), defaultDept());
  } else {
    deptEntity = Object.assign(unref(deptEntity), defaultDept());
  }
}
/**
 * 用户的角色信息
 */
async function userRoleList() {
  const data = await roleInfoByUserId({ id: userEntity.id });
  roleList.value = data ? data : [];
}

const loadUserPosition = async (res: any) => {
  return await userPositionPage({ ...{ id: userEntity.id }, ...res });
};
/**
 * 用户详情切换
 * @param value 
 */
function handleUpdateValue(value: string) {
  spinShow.value = true;
  tabKey.value = value;
  setTimeout(async () => {
    if (value === "tenant") {
      tenantInfo();
    }
    if (value === "dept") {
      userDeptInfo();
    }
    if (value === "role") {
      userRoleList();
    }
    // if (value === "postion") {
    //   reloadPsitionTable();
    // }
    spinShow.value = false;
  }, 300);
}
async function handleAuthRole(record: Recordable) {
  showRoleModal.value = true;
  editRoleTitle.value = `为用户${record.name}授权`;
  const data = await roleInfoByUserId({ id: record.id });
  let roleIds: any = [];
  if (data !== null) {
    data.forEach(item => {
      roleIds.push(item.id);
    })
  }
  const values = { userId: record.id, roleIds: roleIds }
  roleFromValues = Object.assign(roleFromValues, values);
}

function handleColseRole() {
  showRoleModal.value = false;
}
function handleUpdateRole(value: string) {
  roleFromValues = Object.assign(roleFromValues, { roleIds: value });
}
/**
 * 授权提交数据
 * @param e 
 */
async function confirmRoleForm() {
  formBtnLoading.value = true;
  if (roleFromValues.roleIds === null) {
    message.error('请先选择角色');
    return;
  }
  showRoleModal.value = false;
  const data = await saveBatchUserRole(roleFromValues);
  if (data.code !== ResultEnum.SUCCESS) {
    const resultMsg = data.data ? data.data : '';
    message.error(data.mesg + '-' + resultMsg);
  }
  if (data.code === ResultEnum.SUCCESS) {
    message.success(data.mesg);
    showRoleModal.value = false;
  }
  formBtnLoading.value = false;
}
function onExpandedKeys(keys) {
  expandedKeys.value = keys;
}
/**
 * 性别
 */
async function getSexOptions() {
  const data = await dictGroup({ dictGroup: 'user_sex' });
  const arry = data.map(item => ({ label: item.dictName, value: parseInt(item.dictValue) }));
  sexOptions.value = arry;
}
const loadPosition = async () => {
  const treeList = await positionTree({});
  treeData.value = treeList;
}
onMounted(() => {
  getDeptTree();
  getRoleList();
  getSexOptions();
  loadPosition();
});

</script>

<style lang="less" scoped>
.moss-segment {
  margin-top: 15px;
}
</style>
